const { DataTypes, Model, Deferrable, TINYINT, Op } = require("sequelize");
const sequelize = require("../../db/sequelize");
const OrderItem = require("./order_item");
const Cart = require("../cart/cart");
const User = require("../user/user");
const GoodsSkus = require("../goods/goods_skus");
const Goods = require("../goods/goods");
/**
 * 商品订单模型
 */
class Order extends Model {
    static async addOrder(user_id, cart_ids, address) {
        //获取收货地址
        //创建订单
        let order =await this.create({
            user_id: user_id,
            total_price: 0,
            address: JSON.stringify(address)
        })
        //将提交的cart_id加入order_item
        let asyncList=[]
        cart_ids.forEach(async (value) => {
            asyncList.push((async ()=>{
                let cart = await Cart.getCartOne(value, user_id)
                if (cart==null) {
                    throw Error("购物车不存在",{cart_id:value})
                }
                let goods_id = cart.goods_id
                let goods_skus_id = cart.goods_skus_id
                let num = cart.num
                try{
                     let orderItem = await OrderItem.addOrderItem(order.id, goods_id, goods_skus_id, user_id, num)
                     order.total_price += orderItem.price//增加总订单价格
                }catch(err){
                    console.log("错误捕获：",err);
                }
            })())
        })
        //等待异步任务完成
        await Promise.all(asyncList)

        await order.save()//保存结果
        await Cart.delete(user_id, cart_ids)//从购物车中移除
        setTimeout(() => {
            order.set({
                closed: 1
            })
        }, 1000 * 60 * 10)//10分钟后关闭订单
        return order
    }
    static async getList(user_id) {
        let where = {
            user_id: user_id,
            [Op.or]: [
                {
                    closed: 0
                }, {
                    paid_time: {
                        [Op.not]: null
                    }
                }
            ]
        }
        let json = { "list": [], "totalCount": 0 }
        let row = await this.findAll({
            where:where,
            include:[
                {
                    model:OrderItem,
                    include:[
                        {
                            model:GoodsSkus
                        },
                        {
                            model:Goods,
                            attributes:["title","cover"],
                            as:"goods_item"
                        }
                    ]
                },{
                    model:User,
                    attributes:["nickname","username","avatar"]
                }
            ]
        })
        row.forEach(value => {
            json.list.push(value.toJSON())
        })
        json.totalCount=json.list.length
        return json

    }
    static async delete(user_id,id){
        return await this.destroy({
            where:{
                user_id:user_id,
                id:id
            }
        })
    }
};
Order.init({
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    no: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4//自动生成流水号
    },
    user_id: {
        type: DataTypes.INTEGER
    },
    address: {
        type: DataTypes.TEXT,
        get(){
            return JSON.parse(this.getDataValue("address"))
        }
    },
    total_price: {
        type: DataTypes.DECIMAL(10, 2)
    },
    remark: {
        type: DataTypes.STRING
    },
    paid_time: {
        type: DataTypes.DATE
    },
    payment_method: {
        type: DataTypes.STRING
    },
    payment_no: {
        type: DataTypes.STRING
    },
    refund_status: {
        type: DataTypes.STRING
    },
    refund_no: {
        type: DataTypes.STRING
    },
    closed: {
        type: DataTypes.TINYINT(1),
        defaultValue: 0
    },
    ship_status: {
        type: DataTypes.STRING
    },
    ship_data: {
        type: DataTypes.TEXT,
    },
    extra: {
        type: DataTypes.TEXT
    },
    reviewed: {
        type: DataTypes.TINYINT(1)
    },
    coupon_user_id: {
        type: DataTypes.INTEGER
    }
}, {
    sequelize,
    modelName: "Order",
    tableName: "order",
    createdAt: "create_time",
    updatedAt: "update_time",
})
module.exports = Order